// 全局变量
let isCollecting = false;
let bookId = '';
let interval = 5000; // 默认5秒
let collectedContent = '';
let currentChapter = 1;

// 状态管理函数
async function updateCollectionStatus(status) {
  try {
    log(`[状态] 准备更新采集状态: ${JSON.stringify(status)}`);
    await chrome.storage.local.set({
      collectionStatus: status
    });
    log(`[状态] 采集状态已更新: ${JSON.stringify(status)}`);
    
    // 同步更新本地变量
    isCollecting = status.isCollecting;
    if (status.bookId) {
      bookId = status.bookId;
    }
    if (status.interval) {
      interval = status.interval;
    }
  } catch (error) {
    log(`[错误] 更新采集状态失败: ${error.message}`);
    console.error('[错误] 更新采集状态失败:', error);
    throw error;
  }
}

// 获取采集状态
async function getCollectionStatus() {
  try {
    log('[状态] 获取采集状态');
    const result = await chrome.storage.local.get('collectionStatus');
    const status = result.collectionStatus || {
      isCollecting: false,
      bookId: '',
      interval: 5000
    };
    log(`[状态] 当前采集状态: ${JSON.stringify(status)}`);
    
    // 同步更新本地变量
    isCollecting = status.isCollecting;
    if (status.bookId) {
      bookId = status.bookId;
    }
    if (status.interval) {
      interval = status.interval;
    }
    
    return status;
  } catch (error) {
    log(`[错误] 获取采集状态失败: ${error.message}`);
    console.error('[错误] 获取采集状态失败:', error);
    return {
      isCollecting: false,
      bookId: '',
      interval: 5000
    };
  }
}

// 监听来自popup的消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  log('[消息] 收到消息: ' + JSON.stringify(message));
  
  try {
    if (message.action === 'start') {
      log('[消息] 开始采集任务，书籍ID: ' + message.bookId);
      bookId = message.bookId;
      interval = message.interval ? message.interval * 1000 : 5000; // 使用传入的间隔或默认5秒
      
      if (!isCollecting) {
        isCollecting = true;
        // 保存采集状态到storage
        updateCollectionStatus({
          isCollecting: true,
          bookId: bookId,
          interval: interval
        }).then(() => {
          log(`[消息] 已更新采集状态: isCollecting=${isCollecting}, bookId=${bookId}`);
          startCollection();
          sendResponse({ status: 'started' });
        }).catch(error => {
          log(`[错误] 更新采集状态失败: ${error.message}`);
          sendResponse({ status: 'error', error: error.message });
        });
        return true; // 保持消息通道开放
      }
    } else if (message.action === 'stop') {
      isCollecting = false;
      if (pageCheckInterval) {
        clearInterval(pageCheckInterval);
      }
      // 清除采集状态
      updateCollectionStatus({
        isCollecting: false,
        bookId: '',
        interval: 5000
      }).then(() => {
        log('[消息] 采集已停止');
        sendResponse({ status: 'stopped' });
      }).catch(error => {
        log(`[错误] 更新采集状态失败: ${error.message}`);
        sendResponse({ status: 'error', error: error.message });
      });
      return true; // 保持消息通道开放
    }
  } catch (error) {
    log(`[错误] 处理消息出错: ${error.message}`);
    console.error('[错误] 处理消息出错:', error);
    sendResponse({ status: 'error', error: error.message });
  }
  return true; // 保持消息通道开放
});

// 开始采集
async function startCollection() {
  log('[开始] 开始采集任务');
  log('[开始] 当前页面URL: ' + window.location.href);
  
  if (window.location.href.includes('/ebook/')) {
    log('[开始] 当前在书籍详情页面，尝试点击"立即阅读"按钮');
    const readButtons = Array.from(document.querySelectorAll('.details-btn'));
    const readButton = readButtons.find(btn => btn.textContent.includes('立即阅读'));
    
    if (readButton) {
      // 先更新采集状态，再点击按钮
      isCollecting = true;
      await updateCollectionStatus({
        isCollecting: true,
        bookId: bookId,
        interval: interval
      });
      log(`[开始] 已更新采集状态: isCollecting=${isCollecting}, bookId=${bookId}`);
      
      readButton.click();
      log('[开始] 已点击"立即阅读"按钮，等待页面加载...');
      startPageCheck(); // 启动页面检查
    } else {
      log('[错误] 未找到"立即阅读"按钮，请确认是否已登录');
    }
  } else if (window.location.href.includes('/readertob/')) {
    log('[开始] 检测到阅读页面，开始采集内容');
    isCollecting = true;
    await updateCollectionStatus({
      isCollecting: true,
      bookId: bookId,
      interval: interval
    });
    log(`[开始] 已更新采集状态: isCollecting=${isCollecting}, bookId=${bookId}`);
    await collectChapterContent();
  }
}

// 记录日志
function log(message) {
  const now = new Date();
  const timeStr = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}:${now.getSeconds().toString().padStart(2, '0')}`;
  const logMessage = `[${timeStr}] ${message}`;
  
  // 发送到popup显示
  chrome.runtime.sendMessage({
    type: 'log',
    content: logMessage
  });
  
  // 同时在控制台显示
  console.log(`[京东读书采集器] ${logMessage}`);
}

// 保存章节采集状态
async function saveChapterState(chapterId) {
  try {
    const result = await chrome.storage.local.get('collectedChapters');
    const collectedChapters = result.collectedChapters || {
      bookId: bookId,
      chapterIds: []
    };
    
    // 如果是新书，重置章节列表
    if (collectedChapters.bookId !== bookId) {
      collectedChapters.bookId = bookId;
      collectedChapters.chapterIds = [];
      log(`开始新书《${bookId}》的采集`);
    }
    
    // 添加新采集的章节ID
    if (!collectedChapters.chapterIds.includes(chapterId)) {
      collectedChapters.chapterIds.push(chapterId);
      await chrome.storage.local.set({ collectedChapters });
      log(`已添加章节到采集列表: ${chapterId}`);
      log(`当前已采集 ${collectedChapters.chapterIds.length} 个章节`);
    }
  } catch (error) {
    log(`保存章节状态出错: ${error.message}`);
  }
}

// 检查章节是否已采集
async function isChapterCollected(chapterId) {
  try {
    const result = await chrome.storage.local.get('collectedChapters');
    const collectedChapters = result.collectedChapters;
    
    if (!collectedChapters || collectedChapters.bookId !== bookId) {
      log(`未找到书籍 ${bookId} 的采集记录`);
      return false;
    }
    
    const isCollected = collectedChapters.chapterIds.includes(chapterId);
    if (isCollected) {
      log(`章节 ${chapterId} 已在采集列表中`);
    }
    return isCollected;
  } catch (error) {
    log(`检查章节状态出错: ${error.message}`);
    return false;
  }
}

// 获取上次采集的章节状态
async function getLastChapterState() {
  const result = await chrome.storage.local.get('currentChapterState');
  return result.currentChapterState;
}

// 采集章节内容
async function collectChapterContent() {
  try {
    if (!bookId) {
      log(`[错误] bookId 未定义，请确保已正确设置`);
      return;
    }

    log(`[采集] 正在查找章节容器，章节ID前缀: chapter-${bookId}`);
    
    // 等待一段时间让页面加载
    await new Promise(resolve => setTimeout(resolve, 3000));
    
    // 获取所有以chapter-开头的div
    const chapterDivs = Array.from(document.querySelectorAll('div[id^="chapter-"]'));
    log(`[采集] 找到 ${chapterDivs.length} 个章节容器`);
    
    if (chapterDivs.length === 0) {
      log(`[错误] 页面上没有找到任何章节容器，可能页面未完全加载`);
      // 重试当前章节
      await new Promise(resolve => setTimeout(resolve, 5000));
      return await collectChapterContent();
    }
    
    // 找到匹配当前bookId的容器
    const chapterContainer = chapterDivs.find(div => div.id.startsWith(`chapter-${bookId}`));
    
    if (!chapterContainer) {
      log(`[错误] 未找到章节容器 chapter-${bookId}`);
      log('[调试] 当前页面所有chapter-前缀的div:');
      chapterDivs.forEach(div => log(`- ${div.id}`));
      
      // 如果在阅读页面但找不到容器，可能需要重新加载
      if (window.location.href.includes('/readertob/')) {
        log(`[处理] 在阅读页面但找不到容器，等待5秒后重试`);
        await new Promise(resolve => setTimeout(resolve, 5000));
        return await collectChapterContent();
      }
      return;
    }
    
    const currentChapterId = chapterContainer.id;
    log(`[采集] 成功找到章节容器: ${currentChapterId}`);
    
    // 解析章节内容
    const chapterContent = parseChapterContent(chapterContainer);
    
    if (!chapterContent || chapterContent.length === 0) {
      log(`[错误] 章节内容为空，可能解析失败`);
      // 重试当前章节
      await new Promise(resolve => setTimeout(resolve, 5000));
      return await collectChapterContent();
    }
    
    log(`[采集] 章节内容解析完成，长度: ${chapterContent.length} 字符`);
    
    // 将内容添加到总内容中
    collectedContent += `${chapterContent}\n\n`;
    
    // 立即保存当前章节内容
    try {
      log(`[发送] 准备发送章节内容，长度: ${chapterContent.length}`);
      
      // 使用 Promise 包装消息发送
      const response = await new Promise((resolve, reject) => {
        try {
          chrome.runtime.sendMessage({
            type: 'saveContent',
            bookId: bookId,
            content: collectedContent,
            isNewChapter: true
          }, (response) => {
            if (chrome.runtime.lastError) {
              reject(new Error(chrome.runtime.lastError.message));
            } else {
              resolve(response || { success: false, error: '未收到有效响应' });
            }
          });
        } catch (error) {
          reject(new Error(`发送消息失败: ${error.message}`));
        }
      });
      
      if (response && response.success) {
        log(`[发送] 章节内容已成功保存`);
      } else {
        const errorMsg = response?.error || '未知错误';
        log(`[发送] 保存失败: ${errorMsg}`);
        throw new Error(`保存失败: ${errorMsg}`);
      }
    } catch (error) {
      log(`[错误] 发送内容时出错: ${error.message}`);
      console.error('[错误] 发送内容时出错:', error);
      // 如果是消息发送失败，等待后重试
      if (error.message.includes('发送消息失败')) {
        log(`[处理] 等待5秒后重试发送`);
        await new Promise(resolve => setTimeout(resolve, 5000));
        return await collectChapterContent();
      }
      throw error;
    }
    
    // 等待指定间隔
    log(`[采集] 等待 ${interval / 1000} 秒后继续下一章`);
    await new Promise(resolve => setTimeout(resolve, interval));
    
    // 点击下一章按钮
    const nextButton = document.querySelector('button.nextChapter.middleChapter, button.nextChapter');
    if (nextButton) {
      nextButton.click();
      log('[采集] 已点击"下一章"按钮');
      
      // 等待页面加载
      await new Promise(resolve => setTimeout(resolve, 3000));
      
      // 继续采集下一章
      return await collectChapterContent();
    } else {
      log('[完成] 未找到"下一章"按钮，采集完成');
      // 更新最终进度为100%
      await chrome.runtime.sendMessage({
        type: 'updateProgress',
        progress: 100
      });
      
      // 保存完整内容
      if (collectedContent) {
        await chrome.runtime.sendMessage({
          type: 'saveContent',
          bookId: bookId,
          content: collectedContent,
          isNewChapter: false
        });
        log('[完成] 已发送完整内容保存请求');
      }
      
      // 更新采集状态
      isCollecting = false;
      if (pageCheckInterval) {
        clearInterval(pageCheckInterval);
      }
      await updateCollectionStatus({
        isCollecting: false,
        bookId: '',
        interval: 5000
      });
      log('[完成] 采集任务已完成，状态已重置');
    }
  } catch (error) {
    log(`[错误] 采集章节出错: ${error.message}`);
    console.error('[错误] 采集章节出错:', error);
    
    // 如果是致命错误，停止采集
    isCollecting = false;
    if (pageCheckInterval) {
      clearInterval(pageCheckInterval);
    }
    await updateCollectionStatus({
      isCollecting: false,
      bookId: '',
      interval: 5000
    });
  }
}

// 解析章节内容
function parseChapterContent(container) {
  let content = '';
  log('[解析] 开始解析章节内容');
  
  // 检查容器是否有效
  if (!container || !container.nodeType) {
    log('[错误] 无效的章节容器');
    return '';
  }
  
  // HTML标签到Markdown的映射规则
  const tagToMarkdown = {
    'h1': (text) => `# ${text}\n\n`,
    'h2': (text) => `## ${text}\n\n`,
    'h3': (text) => `### ${text}\n\n`,
    'h4': (text) => `#### ${text}\n\n`,
    'h5': (text) => `##### ${text}\n\n`,
    'h6': (text) => `###### ${text}\n\n`,
    'p': (text) => `${text}\n\n`,
    'pre': (text) => `\`\`\`\n${text}\n\`\`\`\n\n`,
    'code': (text) => `\`${text}\``,
    'strong': (text) => `**${text}**`,
    'b': (text) => `**${text}**`,
    'em': (text) => `*${text}*`,
    'i': (text) => `*${text}*`,
    'blockquote': (text) => `> ${text}\n\n`,
    'ul': (text) => `${text}\n\n`,
    'ol': (text) => `${text}\n\n`,
    'li': (text) => `- ${text}\n`,
    'img': (element) => {
      const alt = element.alt || '';
      const src = element.src || '';
      return src ? `![${alt}](${src})\n\n` : '';
    },
    'a': (element) => {
      const text = element.textContent?.trim() || '';
      const href = element.href || '';
      return href ? `[${text}](${href})` : text;
    }
  };

  // 递归处理元素及其子元素
  function processElement(element) {
    try {
      // 检查元素是否有效
      if (!element) {
        log('[警告] 收到无效元素');
        return '';
      }

      // 处理文本节点
      if (element.nodeType === Node.TEXT_NODE) {
        const text = element.textContent?.trim() || '';
        return text ? text + ' ' : '';
      }

      // 检查元素节点
      if (element.nodeType !== Node.ELEMENT_NODE) {
        return '';
      }

      // 获取标签名
      const tagName = element.tagName?.toLowerCase() || '';
      if (!tagName) {
        return '';
      }

      let elementContent = '';
      
      // 处理特殊标签
      if (tagName === 'img' || tagName === 'a') {
        return tagToMarkdown[tagName]?.(element) || '';
      }
      
      // 处理其他标签
      if (tagToMarkdown[tagName]) {
        // 处理子元素
        Array.from(element.childNodes || []).forEach(child => {
          elementContent += processElement(child);
        });
        
        // 应用标签对应的Markdown格式
        return tagToMarkdown[tagName](elementContent.trim());
      }
      
      // 处理未知标签
      Array.from(element.childNodes || []).forEach(child => {
        elementContent += processElement(child);
      });
      
      return elementContent;
    } catch (error) {
      log(`[错误] 处理元素时出错: ${error.message}`);
      console.error('[错误] 处理元素时出错:', error);
      return '';
    }
  }
  
  try {
    // 处理所有子元素
    const childrenCount = container.children?.length || 0;
    log(`[解析] 开始处理容器，子元素数量: ${childrenCount}`);
    
    Array.from(container.children || []).forEach((element, index) => {
      const tagName = element.tagName?.toLowerCase() || 'unknown';
      log(`[解析] 处理第 ${index + 1}/${childrenCount} 个子元素: <${tagName}>`);
      content += processElement(element);
    });
    
    // 清理多余的空行
    content = content.replace(/\n{3,}/g, '\n\n').trim();
    
    if (!content) {
      log('[警告] 解析结果为空');
    } else {
      log(`[解析] 完成，内容长度: ${content.length} 字符`);
    }
    
    return content;
  } catch (error) {
    log(`[错误] 解析章节内容时出错: ${error.message}`);
    console.error('[错误] 解析章节内容时出错:', error);
    return '';
  }
}

// 页面加载完成时检查
window.addEventListener('load', async () => {
  log('页面加载完成，当前URL: ' + window.location.href);
  
  try {
    const status = await getCollectionStatus();
    log('获取到采集状态: ' + JSON.stringify(status));
    
    if (status.isCollecting && status.bookId) {
      log('在阅读页面检测到采集任务，开始采集');
      bookId = status.bookId;
      interval = status.interval || 5000;
      isCollecting = true;
      await collectChapterContent();
    } else if (window.location.href.includes('/ebook/')) {
      log('在书籍详情页面，准备点击立即阅读');
      startCollection();
    }
  } catch (error) {
    log('检查采集状态时出错: ' + error.message);
  }
});

// 移除原有的 MutationObserver
// 改用 setInterval 定期检查页面变化
let pageCheckInterval;

// 在开始采集时启动检查
function startPageCheck() {
  if (pageCheckInterval) {
    clearInterval(pageCheckInterval);
  }
  
  pageCheckInterval = setInterval(async () => {
    if (isCollecting) {
      const currentUrl = window.location.href;
      if (currentUrl.includes('/readertob/')) {
        log('检测到阅读页面，准备开始采集');
        clearInterval(pageCheckInterval);
        try {
          const status = await getCollectionStatus();
          if (status.isCollecting && status.bookId) {
            bookId = status.bookId;
            interval = status.interval || 5000;
            await collectChapterContent();
          } else {
            log('未检测到有效的采集状态，停止采集');
            isCollecting = false;
            updateCollectionStatus({
              isCollecting: false,
              bookId: '',
              interval: 5000
            });
          }
        } catch (error) {
          log('检查采集状态时出错: ' + error.message);
          isCollecting = false;
          updateCollectionStatus({
            isCollecting: false,
            bookId: '',
            interval: 5000
          });
        }
      }
    }
  }, 2000); // 缩短检查间隔到2秒
}

// 在停止采集时清除检查间隔
function stopCollection() {
  isCollecting = false;
  if (pageCheckInterval) {
    clearInterval(pageCheckInterval);
  }
  updateCollectionStatus({
    isCollecting: false,
    bookId: '',
    interval: 5000
  });
  log('采集已停止');
}

// 获取采集进度
async function getCollectionProgress() {
  try {
    const result = await chrome.storage.local.get('collectedChapters');
    const collectedChapters = result.collectedChapters;
    
    if (!collectedChapters || collectedChapters.bookId !== bookId) {
      log(`未找到书籍 ${bookId} 的采集进度`);
      return {
        bookId: bookId,
        collectedCount: 0,
        chapters: []
      };
    }
    
    log(`当前采集进度: ${collectedChapters.chapterIds.length} 章`);
    return {
      bookId: collectedChapters.bookId,
      collectedCount: collectedChapters.chapterIds.length,
      chapters: collectedChapters.chapterIds
    };
  } catch (error) {
    log(`获取采集进度出错: ${error.message}`);
    return {
      bookId: bookId,
      collectedCount: 0,
      chapters: []
    };
  }
}

// 在采集完成时更新状态
async function completeCollection() {
  const status = {
    isCollecting: false,
    bookId: '',
    interval: 5000
  };
  await updateCollectionStatus(status);
  log('采集任务已完成，状态已重置');
}